﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Serialization;
using Zo.Config;
using Zo.IoC;
using ZoLone.Logics;
using ZoLone.Zo.Http;

namespace ZoLone
{
    public static class Bootstrapt
    {
        public static void ConfigureServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            //注入链接字符串ServiceLifetime.Transient每次获取的都是新实例
            services.AddDbContext<DataContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Transient);

            services.AddControllersWithViews();
            var serviceProvider = services.BuildServiceProvider();

            AppConfig.options = configuration.GetSection("AppConfig").Get<ConfigOption>();
            IoCManager.Instance.SetServiceProvider(serviceProvider);
            HttpAccessorService.Set(serviceProvider.GetRequiredService<IHttpContextAccessor>());


            //全局配置Json序列化处理不处理任何格式否则它会自动采用驼峰
            services.AddControllers().AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                });

            //自定义视图 
            services.Configure<RazorViewEngineOptions>(item =>
                {
                    item.AreaViewLocationFormats.Add("/Areas/{2}/Views/Sys/{1}/{0}.cshtml");//系统管理
            });

        }

        public static void ConfigureBase(this IApplicationBuilder app, IWebHostEnvironment env)
        {
           
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute(name: "Default", "areas", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
            });

           
        }
    }
}
